<template>
	<div class="home-page">
		<!-- 顶部渐变背景 -->
		<div class="top-gradient">
			<div class="gradient-mask">
				<div class="ellipse ellipse1"></div>
				<div class="ellipse ellipse2"></div>
			</div>
		</div>

		<!-- 语言选择按钮 -->
		<div class="language-switcher">
			<div class="lang-btn" @click="showLanguagePopup = true">
				<div class="lang-icon">
					<span>{{ locale.toUpperCase() }}</span>
				</div>
			</div>
		</div>

		<!-- 语言选择弹窗 -->
		<van-popup
			v-model:show="showLanguagePopup"
			position="right"
			round
			:style="{ width: '80%', maxWidth: '300px' }"
		>
			<div class="language-popup">
				<div class="popup-title">{{ t('language') }}</div>
				<div class="language-list">
					<div
						class="language-item"
						:class="{ active: locale === 'zh' }"
						@click="changeLanguage('zh')"
					>
						<span class="lang-name">中文</span>
						<van-icon
							v-if="locale === 'zh'"
							name="success"
							color="#69D100"
						/>
					</div>
					<div
						class="language-item"
						:class="{ active: locale === 'en' }"
						@click="changeLanguage('en')"
					>
						<span class="lang-name">English</span>
						<van-icon
							v-if="locale === 'en'"
							name="success"
							color="#69D100"
						/>
					</div>
					<div
						class="language-item"
						:class="{ active: locale === 'es' }"
						@click="changeLanguage('es')"
					>
						<span class="lang-name">Español</span>
						<van-icon
							v-if="locale === 'es'"
							name="success"
							color="#69D100"
						/>
					</div>
					<div
						class="language-item"
						:class="{ active: locale === 'fr' }"
						@click="changeLanguage('fr')"
					>
						<span class="lang-name">Français</span>
						<van-icon
							v-if="locale === 'fr'"
							name="success"
							color="#69D100"
						/>
					</div>
				</div>
			</div>
		</van-popup>

		<!-- 顶部内容区域 -->
		<div class="top-content">
			<div class="left-content">
				<!-- 标题 -->
				<div class="page-title">{{ t('title') }}</div>

				<!-- 物流图标 -->
				<div class="logistics-icon">
					<img src="../assets/logo.svg" alt="物流图标" />
				</div>
			</div>
			<div class="right-content">
				<!-- 纸盒图片 -->
				<div class="box-image">
					<img src="../assets/box.svg" alt="纸盒图片" />
				</div>
			</div>
		</div>

		<!-- 基础信息区域 -->
		<van-cell-group class="info-card" :border="false">
			<div class="card-title">{{ t('basicInfo.title') }}</div>
			<div class="info-content">
				<div class="info-row">
					<div class="info-item">
						<span class="info-label"
							>{{ t('basicInfo.name') }}：</span
						>
						<span class="info-value">{{ orderInfo.name }}</span>
					</div>
					<div class="info-item">
						<span class="info-label"
							>{{ t('basicInfo.phone') }}：</span
						>
						<span class="info-value">{{ orderInfo.phone }}</span>
					</div>
				</div>
				<div class="info-row">
					<div class="info-item">
						<span class="info-label"
							>{{ t('basicInfo.goods') }}：</span
						>
						<span class="info-value">{{ orderInfo.goods }}</span>
					</div>
				</div>
				<div class="info-item">
					<span class="info-label"
						>{{ t('basicInfo.address') }}：</span
					>
					<span class="info-value">{{ orderInfo.address }}</span>
				</div>
			</div>
		</van-cell-group>

		<!-- 预约时间区域 -->
		<van-cell-group class="time-card" :border="false">
			<div class="date-section">
				<div class="card-title">{{ t('appointment.title') }}</div>
				<div class="warning-tip">
					<van-icon
						name="warning-o"
						class="warning-icon"
						color="#FFBE28"
						size="16"
					/>
					<span class="warning-text">{{
						t('appointment.warning')
					}}</span>
				</div>

				<!-- 日期选择器 -->
				<div class="date-selector">
					<div
						v-for="(date, index) in dateList"
						:key="index"
						class="date-item"
						:class="{ active: selectedDate === index }"
						@click="selectedDate = index"
					>
						<div class="date-day">{{ date.dayName }}</div>
						<div class="date-num">{{ date.date }}</div>
					</div>
				</div>
			</div>

			<!-- 时段选择 -->
			<div class="time-section">
				<div class="card-title">
					{{ t('appointment.timeSlot.title') }}
				</div>
				<div class="time-selector">
					<div
						v-for="(time, index) in timeSlots"
						:key="index"
						class="time-item"
						:class="{ selected: selectedTimeSlot === index }"
						@click="selectedTimeSlot = index"
					>
						<span>{{ time }}</span>
						<div
							class="check-icon"
							v-if="selectedTimeSlot === index"
						></div>
					</div>
				</div>
			</div>
		</van-cell-group>

		<!-- 联系方式卡片 -->
		<van-cell-group class="contact-card" :border="false">
			<div class="card-title">{{ t('contact.title') }}</div>
			<van-field
				:border="false"
				v-model="secondaryContact.mobile"
				:label="t('contact.mobile')"
				:placeholder="t('contact.placeholder')"
				input-align="right"
				class="custom-field"
			/>
			<van-field
				v-model="secondaryContact.email"
				:label="t('contact.email')"
				:placeholder="t('contact.placeholder')"
				input-align="right"
				class="custom-field"
			/>
		</van-cell-group>

		<!-- 大门信息卡片 -->
		<van-cell-group class="options-card" :border="false">
			<div class="option-row">
				<span class="option-title">{{ t('doorInfo.title') }}</span>
				<div class="custom-radio-buttons">
					<div
						class="custom-radio-btn"
						:class="{ active: doorInfo === t('doorInfo.noDoor') }"
						@click="doorInfo = t('doorInfo.noDoor')"
					>
						{{ t('doorInfo.noDoor') }}
					</div>
					<div
						class="custom-radio-btn"
						:class="{ active: doorInfo === t('doorInfo.hasDoor') }"
						@click="doorInfo = t('doorInfo.hasDoor')"
					>
						{{ t('doorInfo.hasDoor') }}
					</div>
				</div>
			</div>

			<!-- 当选择有大门时显示密码输入框 -->
			<div
				v-if="doorInfo === t('doorInfo.hasDoor')"
				class="door-password-section"
			>
				<div class="password-divider"></div>
				<div class="password-row">
					<div class="required-mark">
						<div class="alert-circle"></div>
						<span class="required-text">必选</span>
					</div>
					<input
						type="text"
						v-model="doorPassword"
						class="password-input"
						:placeholder="
							t('doorInfo.passwordPlaceholder') ||
							'请填写大门密码'
						"
					/>
				</div>
			</div>
		</van-cell-group>

		<!-- 送货方式卡片 -->
		<van-cell-group class="options-card" :border="false">
			<van-cell
				:title="t('delivery.title')"
				is-link
				:value="deliveryPlacementText"
				@click="showDeliveryPicker = true"
				title-class="option-title"
				value-class="select-value"
			/>
			<van-popup
				:show="showDeliveryPicker"
				position="bottom"
				round
				safe-area-inset-bottom
				teleport="body"
			>
				<van-picker
					:columns="deliveryOptions"
					@confirm="onDeliveryConfirm"
					@cancel="showDeliveryPicker = false"
					:default-index="0"
					show-toolbar
					:title="t('delivery.title')"
				/>
			</van-popup>

			<!-- 当选择了摆放方式后显示图片上传 -->
			<div v-if="deliveryPlacement" class="placement-photo-section">
				<div class="photo-divider"></div>
				<div class="photo-row">
					<div class="photo-info">
						<div class="optional-mark">
							{{ t('delivery.photoOptional') || '非必选' }}
						</div>
						<div class="photo-tip">
							{{
								t('delivery.photoPlaceholder') ||
								'请上传摆放位置照片'
							}}
						</div>
					</div>
					<div class="upload-container">
						<van-uploader
							:after-read="afterReadPhoto"
							v-model="placementPhoto"
							:max-count="1"
							:preview-size="60"
							:deletable="true"
							@delete="onDeletePhoto"
						/>
					</div>
				</div>
			</div>
		</van-cell-group>

		<!-- 是否需要安装 -->
		<!-- <van-cell-group class="options-card" :border="false">
      <div class="option-row">
        <span class="option-title">{{ t('installation.title') }}</span>
        <div class="custom-radio-buttons">
          <div class="custom-radio-btn" :class="{ active: needInstallation === '是' }" @click="needInstallation = '是'">{{
            t('installation.yes') }}</div>
          <div class="custom-radio-btn" :class="{ active: needInstallation === '否' }" @click="needInstallation = '否'">{{
            t('installation.no') }}</div>
        </div>
      </div>
    </van-cell-group> -->

		<!-- 是否需要送货上楼 -->
		<!-- <van-cell-group class="options-card" :border="false">
      <div class="option-row">
        <span class="option-title">{{ t('stairs.title') }}</span>
        <div class="custom-radio-buttons">
          <div class="custom-radio-btn" :class="{ active: needUpstairs === '是' }" @click="needUpstairs = '是'">{{
            t('stairs.yes') }}</div>
          <div class="custom-radio-btn" :class="{ active: needUpstairs === '否' }" @click="needUpstairs = '否'">{{
            t('stairs.no') }}</div>
        </div>
      </div>
    </van-cell-group> -->

		<!-- 语言选择区域 -->
		<!-- <van-cell-group class="language-card" :border="false">
			<div class="card-title">{{ t('title') }} - 语言设置</div>
			<div class="language-buttons">
				<div
					class="language-btn"
					:class="{ active: locale === 'zh' }"
					@click="changeLanguage('zh')"
				>
					中文
				</div>
				<div
					class="language-btn"
					:class="{ active: locale === 'en' }"
					@click="changeLanguage('en')"
				>
					English
				</div>
				<div
					class="language-btn"
					:class="{ active: locale === 'es' }"
					@click="changeLanguage('es')"
				>
					Español
				</div>
				<div
					class="language-btn"
					:class="{ active: locale === 'fr' }"
					@click="changeLanguage('fr')"
				>
					Français
				</div>
			</div>
			<div class="debug-info">
				<div class="debug-label">当前语言: {{ locale }}</div>
				<div class="debug-label">浏览器语言: {{ browserLanguage }}</div>
				<van-button size="small" type="primary" @click="showDebugInfo"
					>显示详细信息</van-button
				>
			</div>
		</van-cell-group> -->

		<!-- 确认按钮 - 根据预约状态显示不同内容 -->
		<div class="confirm-btn">
			<van-button
				type="primary"
				block
				round
				color="#69D100"
				@click="hasAppointment ? viewOrderDetail() : submitOrder()"
			>
				{{
					hasAppointment
						? t('successPopup.viewDetails')
						: t('confirm')
				}}
			</van-button>
		</div>

		<!-- 预约成功弹窗 -->
		<van-popup
			v-model:show="showSuccessPopup"
			round
			closeable
			:style="{ width: '250px' }"
		>
			<div class="success-popup">
				<!-- 渐变背景 -->
				<div class="popup-bg"></div>

				<!-- 成功图标 -->
				<div class="success-icon-container">
					<!-- 装饰性圆点作为背景 -->
					<img
						src="@/assets/success_back.svg"
						alt="装饰背景"
						class="success-back"
					/>

					<!-- 成功图标 -->
					<img
						src="@/assets/success.svg"
						alt="成功图标"
						width="59"
						height="59"
						class="success-icon-img"
					/>
				</div>

				<!-- 成功文字 -->
				<div class="success-title" v-fit-text ref="successTitleRef">
					{{ t('successPopup.title') }}
				</div>

				<!-- 上门时间 -->
				<div class="appointment-time">
					{{ t('successPopup.appointmentTime') }}<br />{{
						appointmentTime
					}}
				</div>

				<!-- 扣款提示 -->
				<div class="cancellation-note">
					{{ t('successPopup.cancellationNote') }}
				</div>

				<!-- 查看详情按钮 -->
				<div
					class="detail-btn"
					v-fit-text
					ref="detailBtnRef"
					@click="viewOrderDetail"
				>
					{{ t('successPopup.viewDetails') }}
				</div>
			</div>
		</van-popup>

		<!-- 底部安全区 -->
		<div class="bottom-safe-area"></div>
	</div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { showToast, showLoadingToast, closeToast } from 'vant'
import 'vant/es/toast/style'
import 'vant/es/dialog/style'
import 'vant/es/popup/style'
import 'vant/es/uploader/style'
import type { PickerOption, UploaderFileListItem } from 'vant'
import { useI18n } from 'vue-i18n'
import { setLocale } from '../i18n'
import { useRouter, useRoute } from 'vue-router'
import { api } from '../utils/request'

const { t, locale } = useI18n()
const router = useRouter()
const route = useRoute()

// 存储浏览器语言信息
const browserLanguage = ref(navigator.language)
const browserPreferredLanguages = ref(navigator.languages)

// 存储API返回的数据
const appointmentData = ref<any>(null)

// 初始化跟踪号 - 从URL参数获取，而非使用默认值
const trackingNumber = ref('')
const trackingNumberError = ref(false)
const hasAppointment = ref(false) // 是否已预约

// 上门时间
const appointmentTime = ref('2025.03.18 14:00-17:00')

// 预约成功弹窗状态
const showSuccessPopup = ref(false)

// 语言选择弹窗状态
const showLanguagePopup = ref(false)

// 监控v-fit-text指令执行情况
const successTitleRef = ref<HTMLElement | null>(null)
const detailBtnRef = ref<HTMLElement | null>(null)

// 获取预约信息
async function fetchAppointmentInfo() {
	try {
		// 先检查URL参数中是否有追踪号
		if (route.query.tracking_number) {
			trackingNumber.value = route.query.tracking_number as string
			console.log('从URL获取追踪号:', trackingNumber.value)
		}
		// 然后检查localStorage
		else if (localStorage.getItem('current_tracking_number')) {
			trackingNumber.value =
				localStorage.getItem('current_tracking_number') || ''
			console.log('从localStorage获取追踪号:', trackingNumber.value)
		}

		// 如果没有追踪号，显示错误提示并返回
		if (!trackingNumber.value) {
			console.error('未找到有效的追踪号')
			trackingNumberError.value = true
			showToast({
				message: t('errors.noTrackingNumber'),
				position: 'middle',
				type: 'fail',
				duration: 3000,
			})
			return
		}

		console.log('开始获取预约信息, 跟踪号:', trackingNumber.value)

		const response = await api.getAppointmentInfo(trackingNumber.value)
		console.log('获取预约API响应:', response)

		closeToast()

		if (response.code === 0) {
			appointmentData.value = response.data
			console.log('获取到的预约数据:', appointmentData.value)

			// 更新页面数据
			updatePageData()

			// 判断是否已经预约
			if (appointmentData.value && appointmentData.value.info) {
				const { info } = appointmentData.value
				console.log('预约状态信息:', info.is_appointment)

				// 检查是否处于编辑模式
				const isEditingMode =
					route.query.mode === 'edit_appointment' ||
					route.query.edit === 'true' ||
					localStorage.getItem('edit_appointment') === 'true'

				console.log('是否处于编辑模式:', isEditingMode)

				// 如果处于编辑模式，则强制设置为未预约状态
				if (isEditingMode) {
					hasAppointment.value = false
					showSuccessPopup.value = false
					console.log('当前处于编辑模式，不显示预约成功弹窗')
				} else {
					// 如果不是编辑模式，则正常设置预约状态
					hasAppointment.value = info.is_appointment === 1
					console.log('已设置预约状态:', hasAppointment.value)

					// 如果已预约，显示成功弹窗
					if (hasAppointment.value) {
						console.log('用户已预约，准备显示成功弹窗')

						// 设置预约时间
						if (info.appointment_year) {
							const formattedDate = `${info.appointment_year}.${info.appointment_month}.${info.appointment_day}`
							appointmentTime.value = `${formattedDate} ${
								info.appointment_time || ''
							}`
							console.log('设置预约时间:', appointmentTime.value)
						}

						// 显示成功弹窗
						showSuccessPopup.value = true
						console.log('成功弹窗显示状态:', showSuccessPopup.value)
					} else {
						console.log('用户未预约，不显示弹窗')
					}
				}
			} else {
				console.log('API返回数据中没有info字段，无法判断预约状态')
			}
		} else {
			console.error(
				'API返回错误状态码:',
				response.code,
				'错误消息:',
				response.msg
			)
			showToast({
				message: response.msg || '获取预约信息失败',
				position: 'middle',
				type: 'fail',
			})
		}
	} catch (error) {
		closeToast()
		console.error('获取预约信息出错:', error)
		showToast({
			message: '网络请求失败，请稍后再试',
			position: 'middle',
			type: 'fail',
		})
	}
}

// 更新页面数据
function updatePageData() {
	if (!appointmentData.value) return

	const { info, config } = appointmentData.value

	// 更新基本信息
	orderInfo.value = {
		name: info.customer_name || '',
		phone: info.mobile || '',
		goods: info.box_info || '',
		address: info.address || '',
	}

	// 更新第二联系方式信息
	secondaryContact.value.mobile = info.other_mobile || ''
	secondaryContact.value.email = info.other_email || ''
	console.log('更新第二联系方式:', secondaryContact.value)

	// 更新大门信息 - 使用多语言
	if (info.is_gate === 1) {
		doorInfo.value = t('doorInfo.hasDoor')
		doorPassword.value = info.gate_code || ''
	} else {
		doorInfo.value = t('doorInfo.noDoor')
	}

	// 更新摆放方式
	if (
		info.storage_place > 0 &&
		config.storage_list &&
		config.storage_list.length > 0
	) {
		const placeIndex = info.storage_place - 1
		if (placeIndex >= 0 && placeIndex < config.storage_list.length) {
			deliveryPlacement.value = config.storage_list[placeIndex]
		}
	}
	if (info.storage_place_url !== '') {
		placementPhoto.value = [{ url: info.storage_place_url }]
	}
	// 如果有预约信息，设置已选择的日期和时间
	if (info.is_appointment === 1 && info.appointment_year) {
		// 在现有日期列表中查找匹配项
		const dateIndex = dateList.value.findIndex((d: { fullDate: Date }) => {
			const dDate = new Date(d.fullDate)
			return (
				dDate.getFullYear() === parseInt(info.appointment_year) &&
				dDate.getMonth() + 1 === parseInt(info.appointment_month) &&
				dDate.getDate() === parseInt(info.appointment_day)
			)
		})

		if (dateIndex >= 0) {
			selectedDate.value = dateIndex
		}

		// 在时间列表中查找匹配项
		if (info.appointment_time) {
			const timeIndex = timeSlots.value.findIndex(
				(t: string) => t === info.appointment_time
			)
			if (timeIndex >= 0) {
				selectedTimeSlot.value = timeIndex
			}
		}
	}
}

// 添加生命周期钩子，在组件挂载时记录语言设置和获取预约信息
onMounted(() => {
	console.log('Home组件挂载 - 当前语言:', locale.value)
	console.log('浏览器语言:', browserLanguage.value)
	console.log('偏好语言列表:', browserPreferredLanguages.value)
	console.log('URL参数:', route.query)

	// 1. 首先检查URL中是否有语言参数 (最高优先级)
	if (route.query.lang && typeof route.query.lang === 'string') {
		console.log('检测到URL中的语言参数:', route.query.lang)
		setLocale(route.query.lang)
	}
	// 2. 其次检查localStorage中是否有用户之前保存的语言偏好
	else if (localStorage.getItem('userLanguage')) {
		const savedLanguage = localStorage.getItem('userLanguage')
		console.log('从localStorage检测到语言偏好:', savedLanguage)
		if (savedLanguage) {
			setLocale(savedLanguage)
		}
	}
	// 3. 最后检查浏览器的语言设置
	else {
		console.log('使用浏览器语言偏好')
		// 这里会使用默认的语言检测逻辑
	}

	// 检查是否在编辑模式
	const isEditMode = route.query.edit === 'true'
	console.log('是否处于编辑模式:', isEditMode)

	if (isEditMode) {
		// 编辑模式下设置状态
		console.log('当前处于编辑模式，允许重新预约')
		hasAppointment.value = false
		showSuccessPopup.value = false
	}

	checkEditMode()

	// 获取预约信息
	fetchAppointmentInfo()

	// 监控v-fit-text指令
	console.log('v-fit-text监控 - 组件挂载完成')
	setTimeout(() => {
		console.log('成功标题元素:', successTitleRef.value)
		console.log('详情按钮元素:', detailBtnRef.value)

		// 检查元素样式
		if (successTitleRef.value) {
			console.log(
				'成功标题字体大小:',
				getComputedStyle(successTitleRef.value).fontSize
			)
		}
		if (detailBtnRef.value) {
			console.log(
				'详情按钮字体大小:',
				getComputedStyle(detailBtnRef.value).fontSize
			)
		}
	}, 500) // 延迟检查，确保DOM已更新
})

// 添加路由监听
watch(
	[() => route.path, () => route.query],
	() => {
		console.log('路由变化，当前路径:', route.path, '查询参数:', route.query)

		// 检查URL中是否有语言参数
		if (route.query.lang && typeof route.query.lang === 'string') {
			console.log('URL参数中的语言变化为:', route.query.lang)
			setLocale(route.query.lang)
		}

		if (route.path === '/') {
			console.log('当前位于首页')

			// 首先检查是否是从详情页返回的编辑模式
			if (
				route.query.mode === 'edit_appointment' ||
				route.query.edit === 'true'
			) {
				console.log('检测到编辑模式URL参数，设置为编辑状态')
				// 允许重新预约
				hasAppointment.value = false
				showSuccessPopup.value = false
				console.log(
					'根据URL参数设置为编辑模式，当前hasAppointment:',
					hasAppointment.value
				)
			}

			// 然后检查localStorage，两种方式都检查确保不会遗漏
			checkEditMode()
		}
	},
	{ immediate: true }
) // 立即执行一次

// 检查是否从详情页返回（修改预约）
function checkEditMode() {
	const isEditMode = localStorage.getItem('edit_appointment')
	console.log('检查编辑模式标记:', isEditMode)

	if (isEditMode === 'true') {
		// 清除标记
		localStorage.removeItem('edit_appointment')
		// 允许重新预约
		hasAppointment.value = false
		showSuccessPopup.value = false
		console.log(
			'从详情页返回，允许重新预约，当前hasAppointment:',
			hasAppointment.value
		)
	}
}

// 监听语言变化
watch(locale, (newLocale) => {
	console.log('语言已变更为:', newLocale)
	console.log('v-fit-text监控 - 语言变化')

	// 延迟检查，等待DOM更新
	setTimeout(() => {
		console.log(
			'语言变化后 - 成功标题字体大小:',
			successTitleRef.value
				? getComputedStyle(successTitleRef.value).fontSize
				: 'N/A'
		)
		console.log(
			'语言变化后 - 详情按钮字体大小:',
			detailBtnRef.value
				? getComputedStyle(detailBtnRef.value).fontSize
				: 'N/A'
		)

		// 手动触发指令的重新计算
		if (successTitleRef.value && showSuccessPopup.value) {
			console.log('正在手动触发成功标题的fitText计算')
			// 尝试手动触发文本调整
			manualTriggerFitText(successTitleRef.value)
		}

		if (detailBtnRef.value && showSuccessPopup.value) {
			console.log('正在手动触发详情按钮的fitText计算')
			// 尝试手动触发文本调整
			manualTriggerFitText(detailBtnRef.value)
		}
	}, 500)
})

// 手动触发fitText计算的函数
function manualTriggerFitText(element: HTMLElement) {
	// 记录原始字体大小
	const originalFontSize = getComputedStyle(element).fontSize
	console.log('元素原始字体大小:', originalFontSize)

	// 获取容器和文本宽度
	const containerWidth = element.clientWidth

	// 临时克隆节点来测量自然文本宽度
	const tempSpan = document.createElement('span')
	tempSpan.style.position = 'absolute'
	tempSpan.style.visibility = 'hidden'
	tempSpan.style.fontSize = originalFontSize
	tempSpan.style.whiteSpace = 'nowrap'
	tempSpan.textContent = element.textContent
	document.body.appendChild(tempSpan)

	const textWidth = tempSpan.offsetWidth
	document.body.removeChild(tempSpan)

	console.log('容器宽度:', containerWidth, '文本宽度:', textWidth)

	// 如果文本宽度大于容器宽度，计算新的字体大小
	if (textWidth > containerWidth && containerWidth > 0) {
		const ratio = containerWidth / textWidth
		const newSize = parseFloat(originalFontSize) * ratio
		console.log('计算新字体大小:', newSize + 'px')
		element.style.fontSize = newSize + 'px'
		console.log('应用后的字体大小:', getComputedStyle(element).fontSize)
	} else {
		console.log('文本未溢出或容器宽度异常，无需调整')
	}
}

// 手动切换语言的函数
function changeLanguage(lang: string) {
	console.log('尝试切换语言到:', lang)
	if (setLocale(lang)) {
		// showToast({
		// 	message: `语言已切换到: ${lang}`,
		// 	position: 'top',
		// })

		// 关闭语言选择弹窗
		showLanguagePopup.value = false
	}
}

// 显示当前语言和环境信息 - 简化版本，移除调试功能
function showDebugInfo() {
	// 禁用调试功能
	return
}

// 订单基本信息
const orderInfo = ref({
	name: '',
	phone: '',
	goods: '',
	address: '',
})

// 日期选择
const selectedDate = ref(0)

// 生成日期列表
const dateList = computed(() => {
	if (
		appointmentData.value &&
		appointmentData.value.config &&
		appointmentData.value.config.date_list
	) {
		const apiDateList = appointmentData.value.config.date_list
		const days = [
			t('appointment.days.sunday'), // 0
			t('appointment.days.monday'), // 1
			t('appointment.days.tuesday'), // 2
			t('appointment.days.wednesday'), // 3
			t('appointment.days.thursday'), // 4
			t('appointment.days.friday'), // 5
			t('appointment.days.saturday'), // 6
		]

		return apiDateList.map((item: any) => {
			const dayName = days[item.week]
			const formattedDate = `${item.month}.${item.day}`

			// 创建日期对象
			const date = new Date(
				parseInt(item.year),
				parseInt(item.month) - 1,
				parseInt(item.day)
			)

			return {
				dayName,
				date: formattedDate,
				fullDate: date,
			}
		})
	}

	// 如果没有API数据，生成一周的默认日期
	const days = [
		t('appointment.days.today'),
		t('appointment.days.tomorrow'),
		t('appointment.days.wednesday'),
		t('appointment.days.thursday'),
		t('appointment.days.friday'),
		t('appointment.days.saturday'),
		t('appointment.days.sunday'),
	]
	const result = []
	const today = new Date()

	for (let i = 0; i < 7; i++) {
		const date = new Date(today)
		date.setDate(today.getDate() + i)

		// 格式化日期为 MM.DD
		const month = String(date.getMonth() + 1).padStart(2, '0')
		const day = String(date.getDate()).padStart(2, '0')
		const formattedDate = `${month}.${day}`

		result.push({
			dayName: days[i],
			date: formattedDate,
			fullDate: date,
		})
	}

	return result
})

// 时间段选项
const timeSlots = computed(() => {
	if (
		appointmentData.value &&
		appointmentData.value.config &&
		appointmentData.value.config.time_list
	) {
		return appointmentData.value.config.time_list
	}

	// 如果没有API数据，使用默认时间段
	return [
		t('appointment.timeSlot.slot1'),
		t('appointment.timeSlot.slot2'),
		t('appointment.timeSlot.slot3'),
		t('appointment.timeSlot.slot4'),
		t('appointment.timeSlot.slot5'),
	]
})

const selectedTimeSlot = ref(0)

// 第二联系方式
const secondaryContact = ref({
	mobile: '',
	email: '',
})

// 大门信息
const doorInfo = ref(t('doorInfo.hasDoor'))
const doorPassword = ref('')

// 送货摆放方式
const deliveryPlacement = ref('')
const showDeliveryPicker = ref(false)
const placementPhoto = ref<UploaderFileListItem[]>([])

// 配送选项根据语言和API返回数据动态生成
const deliveryOptions = computed(() => {
	if (
		appointmentData.value &&
		appointmentData.value.config &&
		appointmentData.value.config.storage_list
	) {
		return appointmentData.value.config.storage_list.map(
			(place: string) => {
				return { text: place, value: place }
			}
		)
	}

	// 如果没有API数据，使用默认选项
	return [
		{ text: t('delivery.locations.frontPorch'), value: 'frontPorch' },
		{ text: t('delivery.locations.garage'), value: 'garage' },
		{ text: t('delivery.locations.backDoor'), value: 'backDoor' },
		{ text: t('delivery.locations.sideEntrance'), value: 'sideEntrance' },
		{ text: t('delivery.locations.buildingLobby'), value: 'buildingLobby' },
	]
})

// 显示选中的配送位置文本
const deliveryPlacementText = computed(() => {
	if (!deliveryPlacement.value) return t('delivery.placeholder')

	return deliveryPlacement.value
})

function onDeliveryConfirm(value: PickerOption) {
	console.log(`当前值: ${JSON.stringify(value.selectedOptions[0].text)}`)

	if (typeof value === 'object' && Array.isArray(value.selectedOptions)) {
		deliveryPlacement.value = value.selectedOptions[0].text
	}
	showDeliveryPicker.value = false
}

// 提交订单成功后的处理
function submitOrderSuccess() {
	hasAppointment.value = true // 设置为已预约
	showSuccessPopup.value = true
}

// 查看预约详情
function viewOrderDetail() {
	console.log('查看预约详情, 跟踪号:', trackingNumber.value)

	// 保存tracking_number到localStorage
	if (trackingNumber.value) {
		localStorage.setItem('current_tracking_number', trackingNumber.value)
		console.log('已保存跟踪号到localStorage:', trackingNumber.value)
	}

	router.push({
		path: '/order-detail',
		query: { tracking_number: trackingNumber.value },
	})
	showSuccessPopup.value = false
}

// 提交预约订单
async function submitOrder() {
	// 先验证必填项
	if (doorInfo.value === t('doorInfo.hasDoor') && !doorPassword.value) {
		showToast({
			message: t('doorInfo.passwordRequired') || '请填写大门密码',
			position: 'bottom',
			type: 'fail',
		})
		return
	}

	const selectedDateObj = dateList.value[selectedDate.value]
	const selectedTime = timeSlots.value[selectedTimeSlot.value]

	// 更新预约时间显示
	const formattedDate = `${selectedDateObj.fullDate.getFullYear()}.${String(
		selectedDateObj.fullDate.getMonth() + 1
	).padStart(2, '0')}.${String(selectedDateObj.fullDate.getDate()).padStart(
		2,
		'0'
	)}`
	appointmentTime.value = `${formattedDate} ${selectedTime}`

	// 根据API文档构建提交数据
	const orderData: any = {
		tracking_number: trackingNumber.value,
		is_appointment: 1, // 已预约
		appointment_year: String(selectedDateObj.fullDate.getFullYear()),
		appointment_month: String(
			selectedDateObj.fullDate.getMonth() + 1
		).padStart(2, '0'),
		appointment_day: String(selectedDateObj.fullDate.getDate()).padStart(
			2,
			'0'
		),
		appointment_week: selectedDateObj.fullDate.getDay(), // 0-周日 1-周一 ...
		appointment_time_type: selectedTimeSlot.value,
		appointment_time: selectedTime,
		other_mobile: secondaryContact.value.mobile,
		other_email: secondaryContact.value.email,
		is_gate: doorInfo.value === t('doorInfo.hasDoor') ? 1 : 2, // 1-有大门 2-无大门
		gate_code:
			doorInfo.value === t('doorInfo.hasDoor') ? doorPassword.value : '',
		storage_place: getStoragePlaceValue(),
		// 如果有图片，转为base64流
		gate_stream: '',
		upstairs_stream: '',
		is_upstairs: 2, // 不需要上楼
		is_installation: 2, // 不需要安装
	}

	// 如果有摆放位置照片，添加到请求中
	if (placementPhoto.value.length > 0 && placementPhoto.value[0].content) {
		orderData.storage_stream = placementPhoto.value[0].content
		// orderData.gate_stream = placementPhoto.value[0].content;
	}

	console.log('提交订单数据：', orderData)

	// 提交订单到API
	const success = await submitOrderToAPI(orderData)

	if (success) {
		// 提交订单后跳转到预约详情页面
		submitOrderSuccess()
	}
}

// 获取摆放位置对应的API值
function getStoragePlaceValue() {
	if (!deliveryPlacement.value) return 0

	// 如果是从API获取的存储列表，需要找到对应的索引+1
	if (
		appointmentData.value &&
		appointmentData.value.config &&
		appointmentData.value.config.storage_list
	) {
		const index = appointmentData.value.config.storage_list.findIndex(
			(place: string) => place === deliveryPlacement.value
		)
		if (index >= 0) {
			return index + 1
		}
	}

	// 如果是默认列表，根据value获取索引
	const defaultOptions = [
		'frontPorch',
		'garage',
		'backDoor',
		'sideEntrance',
		'buildingLobby',
	]
	const index = defaultOptions.indexOf(deliveryPlacement.value)
	return index >= 0 ? index + 1 : 0
}

// 实际提交订单到API
async function submitOrderToAPI(orderData: any) {
	try {
		showLoadingToast({
			message: 'Loading...',
			forbidClick: true,
		})

		// 使用API方法提交订单
		const response = await api.submitAppointment(orderData)
		console.log('提交预约API响应:', response)

		closeToast()

		if (response.code === 0) {
			// 如果API返回跟踪号，更新本地跟踪号
			if (response.data && response.data.tracking_number) {
				console.log('获取到新的跟踪号:', response.data.tracking_number)
				trackingNumber.value = response.data.tracking_number
			}

			return true
		} else {
			showToast({
				message: response.msg || '提交失败',
				position: 'middle',
				type: 'fail',
			})
			return false
		}
	} catch (error) {
		closeToast()
		console.error('提交订单出错:', error)
		showToast({
			message: '网络请求失败，请稍后再试',
			position: 'middle',
			type: 'fail',
		})
		return false
	}
}

// 处理图片上传后的操作
function afterReadPhoto() {
	console.log('上传的图片:', placementPhoto.value)
	// 显示上传成功提示
	// showToast({
	//   message: t('delivery.photoUploadSuccess') || '图片上传成功',
	//   position: 'bottom',
	// });

	// 也可以在这里上传图片到服务器
	// uploadPhotoToServer(processedFiles);
}

function onDeletePhoto(file: UploaderFileListItem) {
	// 简单根据url删除图片
	placementPhoto.value = placementPhoto.value.filter(
		(f) => f.url !== file.url
	)
	console.log('删除后图片:', placementPhoto.value)

	// 显示删除成功提示
	showToast({
		message: t('delivery.photoDeleted') || '图片已删除',
		position: 'bottom',
	})
}
</script>

<style lang="scss" scoped>
// 添加全局样式重置
:deep(*) {
	box-sizing: border-box;
}

// 变量定义
$primary-color: #69d100;
$secondary-color: #3a3a3a;
$background-color: #f3f4f6;
$card-bg-color: #ffffff;
$text-color: #000000;
$gray-text: #a4a4a4;
$dark-gray-text: #595959;
$light-gray-bg: #ebf3df;
$warning-color: #ffbe28;

// 语言切换按钮
.language-switcher {
	position: absolute;
	top: 15px;
	z-index: 100;
	background-color: transparent;
	max-width: 50px;
	min-width: 43px;
	justify-content: center;
	box-shadow: none;
	// width: 40px;
	.lang-btn {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		// background-color: rgba(255, 255, 255, 0.7);
		// backdrop-filter: blur(4px);
		// box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		display: flex;
		justify-content: center;
		align-items: center;
		cursor: pointer;
		transition: all 0.2s ease;

		&:hover {
			background-color: rgba(255, 255, 255, 0.9);
		}

		.lang-icon {
			font-size: 14px;
			font-weight: 700;
			color: $secondary-color;
		}
	}
}

// 语言选择弹窗
.language-popup {
	padding: 20px;

	.popup-title {
		font-size: 18px;
		font-weight: 700;
		margin-bottom: 15px;
		text-align: center;
		color: $secondary-color;
	}

	.language-list {
		display: flex;
		flex-direction: column;
		gap: 15px;

		.language-item {
			display: flex;
			justify-content: space-between;
			align-items: center;
			padding: 10px 15px;
			border-radius: 8px;
			background-color: #f5f5f5;
			cursor: pointer;
			transition: all 0.2s ease;

			&:hover {
				background-color: #efefef;
			}

			&.active {
				background-color: $light-gray-bg;
			}

			.lang-name {
				font-size: 16px;
				font-weight: 600;
				color: $secondary-color;
			}
		}
	}
}

// 基础样式
.home-page {
	min-height: 100vh;
	background-color: $background-color;
	position: relative;
	padding-bottom: 80px;
	margin: 0;
	padding-top: 40px;
}

// 顶部内容区域样式
.top-content {
	display: flex;
	align-items: center;
	justify-content: center;
	padding: 0 20px;
	position: relative;
	z-index: 5;
	margin-top: 0;
	margin-bottom: 10px;
}

.left-content {
	display: flex;
	flex-direction: column;
	align-items: flex-start;
	justify-content: center;
	flex: 1;
}

.right-content {
	display: flex;
	justify-content: center;
	align-items: center;
	flex: 1;
	position: relative;
	z-index: 20;
}

.box-image {
	width: 148px;
	height: 136px;
	display: flex;
	justify-content: center;
	align-items: center;
	position: relative;
	bottom: -25px;
	z-index: 20;

	img {
		max-width: 100%;
		max-height: 100%;
	}
}

// 顶部渐变背景
.top-gradient {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 200px;
	background: linear-gradient(135deg, #e9f8d7, #c6eefc);
	z-index: 1;
	margin-top: 0;

	.gradient-mask {
		position: relative;
		width: 100%;
		height: 100%;
		overflow: hidden;

		.ellipse {
			position: absolute;
			border-radius: 50%;
			filter: blur(100px);

			&.ellipse1 {
				width: 150px;
				height: 150px;
				background: rgba(255, 255, 255, 0.7);
				top: -20px;
				right: 20px;
			}

			&.ellipse2 {
				width: 120px;
				height: 120px;
				background: rgba(255, 255, 255, 0.5);
				top: 50px;
				left: 30px;
			}
		}
	}
}

// 页面标题 - 修改样式，左对齐
.page-title {
	font-family: 'Alimama ShuHeiTi', sans-serif;
	font-weight: 700;
	// background-color: #69D100;
	font-size: 35px;
	position: relative;
	z-index: 2;
	text-align: left;
	margin-bottom: 0px;
}

// 物流图标 - 修改样式，左对齐
.logistics-icon {
	// background-color: #69D100;

	width: 120px;
	height: 50px;
	position: relative;
	z-index: 2;
	display: flex;
	justify-content: flex-start;
	align-items: center;
	margin-bottom: 10px;

	img {
		width: 100px;
		height: 100px;
	}
}

// 卡片基础样式
:deep(.van-cell-group) {
	background-color: $card-bg-color;
	border-radius: 15px;
	padding: 16px;
	margin: 16px;
	position: relative;
	z-index: 2;
	box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
}

// 卡片标题
.card-title {
	font-weight: 600;
	font-size: 16px;
	margin-bottom: 16px;
}

.custom-field {
	margin-top: 16px;
}

// 基础信息卡片
.info-card {
	margin-top: -20px;
	position: relative;
	z-index: 2;

	.info-content {
		display: flex;
		flex-direction: column;
		gap: 16px;
	}

	.info-row {
		display: flex;
		justify-content: space-between;
		gap: 10px;
	}

	.info-item {
		display: flex;
		align-items: center;
		flex: 1;
	}

	.info-label {
		font-size: 12px;
		font-weight: 600;
		color: $gray-text;
		white-space: nowrap;
	}

	.info-value {
		font-size: 12px;
		font-weight: 600;
		color: $dark-gray-text;
		word-break: break-all;
		margin-left: 2px;
	}
}

// 预约时间卡片
.time-card {
	.warning-tip {
		display: flex;
		align-items: center;
		gap: 4px;
		margin-bottom: 16px;

		.warning-text {
			font-size: 12px;
			font-weight: 600;
			color: $warning-color;
		}
	}

	.date-selector {
		display: flex;
		overflow-x: auto;
		gap: 5px;
		margin-bottom: 20px;

		&::-webkit-scrollbar {
			display: none;
		}

		.date-item {
			flex-shrink: 0;
			// width: 60px;
			height: 60px;
			padding: 0 10px;
			background-color: $light-gray-bg;
			border-radius: 10px;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;

			&.active {
				background-color: $primary-color;

				.date-day,
				.date-num {
					color: white;
				}
			}

			.date-day {
				font-size: 15px;
				font-weight: 300;
				color: $secondary-color;
			}

			.date-num {
				font-size: 14px;
				font-weight: 700;
				color: $secondary-color;
			}
		}
	}

	.time-section {
		margin-top: 20px;
	}

	.time-selector {
		display: flex;
		flex-wrap: wrap;
		gap: 9px;

		.time-item {
			width: calc(50% - 4.5px);
			height: 44px;
			background-color: $light-gray-bg;
			border-radius: 10px;
			display: flex;
			align-items: center;
			justify-content: center;
			font-size: 14px;
			font-weight: 700;
			color: $secondary-color;
			position: relative;

			&.selected {
				border: 2px solid $primary-color;

				.check-icon {
					position: absolute;
					top: -8px;
					right: -8px;
					width: 16px;
					height: 16px;
					background-color: $primary-color;
					border-radius: 50%;

					&:after {
						content: '✓';
						color: white;
						font-size: 10px;
						position: absolute;
						top: 50%;
						left: 50%;
						transform: translate(-50%, -50%);
					}
				}
			}
		}
	}
}

// 联系方式卡片
.contact-card {
	:deep(.van-field) {
		padding: 0;
	}

	:deep(.van-field__label) {
		font-weight: 600;
		font-size: 16px;
		width: 4em;
		min-width: 180px;
		// background-color: #69D100;
		color: $text-color;
	}

	:deep(.van-field__control) {
		text-align: right;
		color: #b1b1b2;
	}
}

// 选项卡片
.options-card {
	margin-top: 12px;

	.option-row {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.option-title,
	:deep(.van-cell__title) {
		font-weight: 600;
		font-size: 16px;
	}

	// 大门密码部分样式
	.door-password-section {
		margin-top: 10px;

		.password-divider {
			height: 1px;
			background-color: #b1b1b2;
			margin: 8px 0 12px;
			opacity: 0.5;
		}

		.password-row {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.required-mark {
				display: flex;
				align-items: center;

				.alert-circle {
					width: 18px;
					height: 18px;
					position: relative;

					&:before {
						content: '';
						position: absolute;
						top: 3px;
						left: 3px;
						width: 12px;
						height: 12px;
						background-color: #ff2828;
						border-radius: 50%;
					}
				}

				.required-text {
					margin-left: 5px;
					color: #ff2828;
					font-size: 15px;
					font-weight: 600;
				}
			}

			.password-input {
				width: 165px;
				height: 40px;
				padding: 0 10px;
				background-color: #ececec;
				border-radius: 10px;
				border: none;
				color: #3a3a3a;
				font-size: 15px;
				font-weight: 600;
				text-align: center;

				&::placeholder {
					color: #b1b1b2;
				}

				&:focus {
					outline: none;
					box-shadow: 0 0 0 2px rgba($primary-color, 0.2);
				}
			}
		}
	}

	// 摆放照片部分样式
	.placement-photo-section {
		margin-top: 10px;

		.photo-divider {
			height: 1px;
			background-color: #b1b1b2;
			margin: 8px 0 12px;
			opacity: 0.5;
		}

		.photo-row {
			display: flex;
			justify-content: space-between;
			align-items: center;

			.photo-info {
				display: flex;
				flex-direction: column;
				align-items: flex-start;
				gap: 8px;

				.optional-mark {
					color: $warning-color;
					font-size: 15px;
					font-weight: 600;
				}

				.photo-tip {
					color: #b1b1b2;
					font-size: 15px;
					font-weight: 600;
				}
			}

			.upload-container {
				width: 200px;
				min-height: 56px;
				display: flex;
				justify-content: flex-end;
				align-items: center;
			}
		}
	}

	:deep(.van-radio-group) {
		display: flex;
		gap: 8px;
	}

	:deep(.van-radio) {
		margin-right: 0;
	}

	:deep(.van-radio__label) {
		margin-left: 4px;
		padding: 6px 16px;
		border-radius: 10px;
		font-size: 14px;
		font-weight: 600;
		background-color: #e3e3e3;
		color: #9b9b9b;
	}

	:deep(.van-radio--checked) {
		.van-radio__label {
			background-color: $primary-color;
			color: white;
		}
	}

	:deep(.select-value) {
		font-size: 14px;
		font-weight: 600;
		color: #b1b1b2;
		text-align: right;
		margin-right: 5px;
	}

	:deep(.van-cell) {
		padding: 0;
		background-color: transparent;
		display: flex;
		align-items: center;
		justify-content: space-between;
		min-height: 44px;
	}

	:deep(.van-cell__value) {
		display: flex;
		align-items: center;
		justify-content: flex-end;
		flex: none;
	}

	:deep(.van-cell__right-icon) {
		display: flex;
		align-items: center;
		height: 100%;
		margin-left: 3px;
		position: relative;
		flex: none;
	}

	:deep(.van-icon-arrow) {
		margin: auto 0;
		display: flex;
		align-self: center;
	}
}

// 确认按钮
.confirm-btn {
	margin: 24px 16px;

	:deep(.van-button) {
		height: 50px;
		border-radius: 10px;
		font-size: 20px;
		font-weight: 600;
	}
}

// 底部安全区
.bottom-safe-area {
	height: 20px;
}

// 自定义单选按钮样式
.custom-radio-buttons {
	display: flex;
	gap: 8px;

	.custom-radio-btn {
		padding: 6px 16px;
		border-radius: 10px;
		font-size: 14px;
		font-weight: 600;
		background-color: #e3e3e3;
		color: #9b9b9b;
		cursor: pointer;
		transition: all 0.2s ease;

		&.active {
			background-color: $primary-color;
			color: white;
		}
	}
}

// 预约成功弹窗样式
.success-popup {
	position: relative;
	height: 380px;
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 20px;
	overflow: hidden;

	.popup-bg {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: linear-gradient(180deg, #dbfdb8 0%, #fbfffe 100%);
		z-index: -1;
	}

	.success-icon-container {
		position: relative;
		margin-top: 20px;
		width: 109px;
		height: 69px;
		display: flex;
		justify-content: center;
		align-items: center;

		.success-back {
			position: absolute;
			width: 109px;
			height: 69px;
			z-index: 0;
		}

		.success-icon-img {
			position: relative;
			z-index: 1;
		}
	}

	.success-title {
		margin-top: 15px;
		color: #3c3c3c;
		font-weight: 700;
		text-align: center;
		color: #3c3c3c;
		font-size: 20px;
		font-weight: 700;
		word-wrap: break-word;
	}

	.appointment-time {
		margin-top: 15px;
		text-align: center;
		color: #3c3c3c;
		font-size: 14px;
		font-weight: 600;
		line-height: 1.5;
	}

	.cancellation-note {
		margin-top: 20px;
		width: 200px;
		text-align: center;
		color: #6f4d00;
		font-size: 12px;
		font-weight: 600;
		background-color: #ffeab9;
		padding: 8px 12px;
		border-radius: 8px;
	}

	.detail-btn {
		margin-top: 20px;
		// padding: 2px 10px;
		width: 90%;
		height: 40px;
		text-align: center;
		background: #69d100;
		border-radius: 15px;
		display: flex;
		align-items: center;
		justify-content: center;
		color: white;
		font-size: 16px;
		/* 改为一个合理的初始值 */
		font-weight: 600;
		cursor: pointer;
	}
}
</style>
